import hashlib
import json

from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# from django.contrib.postgres.fields import JSONField

class JSONField(models.TextField):
    __metaclass__ = models.Subquery
    description = "Json"
    def to_python(self, value):
        v = models.TextField.to_python(self, value)
        try:
            return v
        except:
            pass
        return v
    def get_prep_value(self, value):
        return dict(value)

class GeeJoansUser(User):
    Uid=models.AutoField(primary_key=True)
    # username = models.CharField(max_length=50, unique=True)
    # password = models.CharField(max_length=100)
    # email = models.CharField(max_length=100, default='')
    # role = models.CharField(max_length=10, default='user', choices=(('user', '普通用户'), ('admin', '管理员'), ('vip', 'VIP')))
    # Uid=models.IntegerField(primary_key=True)
    # Uname=models.CharField(max_length=32)
    # Upassword=models.CharField(max_length=32)
    # Udatetime=models.DateTimeField(auto_now_add=True)
    # last_active = models.DateField(auto_now_add=True)
    # created_time = models.DateTimeField(auto_now_add=True)
    # last_login = models.DateTimeField(null=True)
    # Ustatus=models.BooleanField(default=True)

    # @property
    # def is_active(self):
    #     return self.role == 'admin'
    #
    # @property
    # def is_staff(self):
    #     return self.role == 'admin'
    #
    # def has_perm(self, *args, **kwargs):
    #     return self.role == 'admin'
    #
    # def has_module_perms(self, *args, **kwargs):
    #     return self.role == 'admin'

    def __str__(self):
        return self.username

# class GeeJoansUser(models.Model):
#     user=models.OneToOneField(User)
#     Uid=models.IntegerField(primary_key=True)
#
#     def create_user_profile(sender, instance, created, **kwargs):
#         """Create the UserProfile when a new User is saved"""
#         if created:
#             profile = GeeJoansUser()
#             profile.user = instance
#             profile.save()
#
#     def __str__(self):
#         return self.user.username

class UserLog(models.Model):
    ULdatatime=models.DateTimeField(auto_now_add=True,primary_key=True)
    Uid=models.ForeignKey(GeeJoansUser,on_delete=models.CASCADE)
    ULip=models.GenericIPAddressField(auto_created=True)
    ULnote=models.CharField(max_length=256)
    # temp = "%s%s%s" %(Uid.username,Uid.password,ULdatatime)
    Uopenid=models.CharField(max_length=32)
    def __str__(self):
        return "%s@%s"%(self.ULdatatime,self.Uopenid)

class UserExpansion(models.Model):
    UEid=models.AutoField(primary_key=True)
    Uid=models.OneToOneField(GeeJoansUser,on_delete=models.CASCADE)
    UEcompany=models.CharField(max_length=256)
    UEposition=models.CharField(max_length=256)
    UEdirection=models.CharField(max_length=256)
    UEother=models.CharField(max_length=256)
    def __str__(self):
        return self.Uid


class ProjectType(models.Model):
    name=models.CharField(primary_key=True,max_length=32)
    def __str__(self):
        return self.name

class ProjectInformation(models.Model):
    Pid=models.AutoField(primary_key=True)
    Uid=models.ForeignKey(GeeJoansUser,on_delete=models.CASCADE)
    Ptype=models.ForeignKey(ProjectType, on_delete=models.CASCADE)
    # Ptype=models.CharField(max_length=32)
    Ptitle=models.CharField(max_length=64)
    Pdescription=models.CharField(max_length=128,blank=True)
    Pnote=models.CharField(max_length=1024,blank=True)
    Pdatatime=models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return "%s@%s"%(self.Pid,self.Ptitle)

# class UserProject(models.Model):
#     UPid=models.AutoField(primary_key=True)
#     Uid=models.ForeignKey(GeeJoansUser,on_delete=models.CASCADE)
#     Pid=models.ForeignKey(ProjectInformation,on_delete=models.CASCADE)
#     UPcreatetime=models.DateTimeField(auto_now_add=True)
#
#     def __str__(self):
#         return "%s@%s"%(self.Uid,self.Pid)

# class ProjectDevices(models.Model):
#     PDid=models.AutoField(primary_key=True)
#     Pid=models.ForeignKey(ProjectInformation,on_delete=models.CASCADE)
#     Did=models.ForeignKey(Devices,on_delete=models.CASCADE)
#     PDdatetime=models.DateTimeField(auto_now_add=True)
#
#     def __str__(self):
#         return "%s@%s"%(self.Pid,self.Did)

    # def toJSON(self):
    #     # import json
    #     # return json.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
    # def toJSON(self):
    #     fields = []
    #     for field in self._meta.fields:
    #         fields.append(field.name)
    #
    #     d = {}
    #     for attr in fields:
    #         d[attr] = getattr(self, attr)
    #
    #     import json
    #     return json.dumps(d)

class Devices(models.Model):
    SENSOR='sensor'
    RELAY='relay'
    OTHER='other'
    Dtype_CHOICES=[(SENSOR,"传感器"),(RELAY,"执行器"),(OTHER,"其他")]
    Did=models.AutoField(primary_key=True)
    Pid=models.ForeignKey(ProjectInformation,on_delete=models.CASCADE)
    Dtype=models.CharField(max_length=8,choices=Dtype_CHOICES,default=SENSOR)
    Dregister=models.CharField(max_length=32)
    Ddatetime=models.DateTimeField(auto_now_add=True)
    Dstatus=models.BooleanField(default=True)
    def __str__(self):
        return self.Dregister


class DevicesStat(models.Model):
    DSdatetime=models.DateTimeField(auto_now_add=True)
    Did=models.ForeignKey(Devices,on_delete=models.CASCADE)
    DSaddr=models.GenericIPAddressField(auto_created=True)
    DSstatus=models.BooleanField(default=True)

    def __str__(self):
        return self.DSdatetime
class ProjectData(models.Model):
    PDid=models.AutoField(primary_key=True)
    Did=models.ForeignKey(Devices,on_delete=models.CASCADE)
    PDdatetime=models.DateTimeField(auto_now_add=True,blank=True)
    PDtype=models.CharField(max_length=512)
    PDdata=models.TextField(max_length=1024)

    def __str__(self):
        return "%s@%s"%(self.Did.Dregister,self.PDdatetime)


class  Member(models.Model):
    username=models.CharField(max_length=150)
    password=models.CharField(max_length=32)
    openid=models.CharField(max_length=32,default=None)
    def __str__(self):
        return self.username